<?php

class Manager_IndexController extends Zend_Controller_Action
{

    protected $formLogin = null;
    protected $dbAdmin = null;
    protected $session = null;
    public function init(){   
           $this->session = new Zend_Session_Namespace('auth');
            $this->formLogin = new Manager_Form_Login();
            $this->dbAdmin = new Manager_Model_Admin(); 
    }

    public function indexAction()
    {
      $this->view->form =  $this->formLogin; 
      $authAdapter = $this->getAuthadapter();
       $request = $this->getRequest();
       if($request->isPost()){
           $dataForm = $request->getPost();
           if($this->formLogin->isValid($dataForm)){
                   $username=$this->formLogin->getValue('username');
                   $password =$this->formLogin->getValue('password');
                   $authAdapter ->setIdentity($username)
                                ->setCredential($password);
                   $auth = Zend_Auth::getInstance();
                  $result = $auth->authenticate($authAdapter);
                   if($result->isValid()){
                       $identity = $authAdapter->getResultRowObject();
                       $authStorage =  $auth->getStorage();
                       $authStorage->write($identity); 
                        $this->session->username= 'marko';
                      $this->_redirect('manager/dashboards');

                   }
                   else
                       {
                            echo "Login Gagal";
                       }
           }
       }
    }
    
     private function getAuthadapter()
    {
         $db = Zend_Registry::get('Zend_Db');
        $authAdapter = new Zend_Auth_Adapter_DbTable($db);
        $authAdapter ->setTableName('admin')
                     ->setIdentityColumn('username')
                     ->setCredentialColumn('password');

        return $authAdapter;
    }

    public function logoutAction(){
         $auth=Zend_Auth::getInstance();
      //If logged in then move to index
         if(!$auth->hasIdentity()){$this->_redirect('/');}
        $auth->clearIdentity();
        Zend_Session::destroy(true);
        $this->_redirect('manager/index/');

   }


}

